package com.huayal.common.exception;

import com.huayal.common.utils.R;
import com.huayal.common.exception.BizCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一的异常处理类
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.huayal.mall.product.controller")
public class ExceptionController {


    /**
     * 参数类型异常的异常处理类
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerValidException(MethodArgumentNotValidException e){

        Map<String, String> map = new HashMap<>();
        e.getBindingResult().getFieldErrors().forEach((fieldError) ->{
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data",map);
    }

    /**
     * 系统其他异常处理类
     * @param throwable
     * @return
     */
    @ExceptionHandler(Throwable.class)
    public R  handleException(Throwable throwable){
        log.error("错误信息："+throwable.getMessage());
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMsg()).put("data",throwable.getMessage());
    }
}
